﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace EmbeddedSensorCloud.HTTP
{
    internal static class Helper
    {
        internal static Dictionary<string, string> ToArguments(string url)
        {
            Dictionary<string, string> resultSet = new Dictionary<string, string>();

            int markIndex = url.IndexOf('?');

            if (markIndex != -1 && markIndex+1 < url.Length)
            {
                string parameterString = url.Substring(markIndex + 1);
                var parameters = HttpUtility.ParseQueryString(parameterString);

                if (parameters != null)
                {
                    foreach (string key in parameters)
                    {
                        resultSet.Add(key, parameters[key]);
                    }
                }
            }

            return resultSet;
        }

        internal static string TooUrlWithoutArguments(string url)
        {
            int markIndex = url.IndexOf('?');

            if (markIndex >= 0)
            {
                return url.Substring(0, markIndex);
            }

            return url;
        }

        internal static Version ToHTTPVersion(string httpVersion)
        {
            switch (httpVersion)
            {
                case "HTTP/1.0":
                default:
                    return HttpVersion.Version10;
                case "HTTP/1.1":
                    return HttpVersion.Version11;
            }
        }

        internal static KeyValuePair<string, string> ToHeader(string line)
        {
            var separator = line.IndexOf(':');
            if (separator <= 0)
            {
                throw new Exception("Invalid http header line: " + line);
            }

            var key = line.Substring(0, separator);
            var pos = separator + 1;
            while (pos < line.Length && line[pos] == ' ')
            {
                pos++; // strip any spaces
            }

            var value = line.Substring(pos);
            return new KeyValuePair<string, string>(key, value);
        }
    }
}
